<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <div class="mx-auto py-6">
      <!-- 第一行：数据概览 -->
      <!--  <div class="grid grid-cols-3 gap-6 mb-6">
        <div v-for="(item, index) in overviewData" :key="index" class="bg-white rounded-lg p-4 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900">{{ item.title }}</h3>
            <div class="flex space-x-2">
              <el-button type="primary" size="small" class="!rounded-button whitespace-nowrap">
                {{ item.viewMode }}
              </el-button>
            </div>
          </div>
          <div class="flex justify-between items-center">
            <div>
              <div class="text-3xl font-semibold text-gray-900">{{ item.total }}</div>
              <div class="text-sm text-gray-500 mt-2">总数</div>
            </div>
            <div v-if="item.unassigned !== undefined" class="text-center">
              <div class="text-2xl font-medium text-orange-500">{{ item.unassigned }}</div>
              <div class="text-sm text-gray-500 mt-2">待分配</div>
            </div>
            <div>
              <div class="text-2xl font-medium text-blue-600">{{ item.personal }}</div>
              <div class="text-sm text-gray-500 mt-2">我的</div>
            </div>
          </div>
          <div class="h-[80px] mt-4">
            <div ref="chartRefs[index]" class="w-full h-full"></div>
          </div>
        </div>
      </div> -->
      <!-- 第二行：详细数据 -->
      <div class="grid grid-cols-2 gap-6 mb-6">
        <!-- 需求列表 -->
        <div class="bg-white rounded-lg p-4 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3
              class="text-xl md:text-2xl font-semibold text-gray-800 dark:text-gray-100 tracking-tight border-b border-blue-200 pb-2">
              今日超时任务
            </h3>
            <div class="flex space-x-2">
              <el-button-group>
                <el-button :type="myOrAllTimeOutIcs === 'all' ? 'primary' : 'default'" size="small"
                  class="!rounded-button whitespace-nowrap" @click="toggleView('all')">
                  全部
                </el-button>
                <el-button :type="myOrAllTimeOutIcs === 'my' ? 'primary' : 'default'" size="small"
                  class="!rounded-button whitespace-nowrap" @click="toggleView('my')">
                  我的
                </el-button>
              </el-button-group>
            </div>
          </div>

          <el-table v-loading="requirementLoading" :data="timeOutTableData" style="width: 100%" :max-height="300"
            @row-click="handleRequirementInfo" highlight-current-row :current-row-key="currentRowId">
            <el-table-column prop="itemRequirementName" label="需求名称" width="480" />
            <el-table-column prop="isOutTime" label="是否超时" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isOutTime === '是' ? 'danger' : 'success'">
                  {{ scope.row.isOutTime }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="责任人" width="100" />
            <el-table-column prop="guessTime" label="要求完成时间" />
          </el-table>
        </div>
        <!-- bug动态 -->
        <div class="bg-white rounded-lg p-4 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3
              class="text-xl md:text-2xl font-semibold text-gray-800 dark:text-gray-100 tracking-tight border-b border-blue-200 pb-2">
              缺陷动态
            </h3>
            <div class="flex space-x-2">
              <el-button-group>
                <el-button :type="myOrAllBugList === 'all' ? 'primary' : 'default'" size="small"
                  class="!rounded-button whitespace-nowrap" @click="toggleBugView('all')">
                  全部
                </el-button>
                <el-button :type="myOrAllBugList === 'my' ? 'primary' : 'default'" size="small"
                  class="!rounded-button whitespace-nowrap" @click="toggleBugView('my')">
                  我的
                </el-button>
              </el-button-group>
            </div>
          </div>

          <el-table v-loading="bugListLoading" :data="bugListTableData" style="width: 100%" :max-height="300"
            @row-click="handleRBugInfo">
            <el-table-column prop="itemItemId" label="项目名称" width="80">
              <template #default="scope">
                <el-tag>
                  {{ getItemName(scope.row.itemItemId) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ID" label="缺陷ID" width="100" />
            <el-table-column prop="bug_title" label="缺陷标题" width="350" />
            <el-table-column prop="create_user_name" label="创建人" width="80" />
            <el-table-column prop="edit_user_names" label="修复人" width="80" />
            <el-table-column prop="bug_status" label="bug状态" width="80">
              <template #default="scope">
                <el-tag
                  :style="{ backgroundColor: getBugStatusColor(scope.row.bug_status), color: getBugLevelTextColor2(scope.row.bug_level) }"
                  size="small">
                  {{ getBugStatusName(scope.row.bug_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="bug_level" label="严重等级" width="80">
              <template #default="scope">
                <el-tag
                  :style="{ backgroundColor: getBugLevelColor2(scope.row.bug_level), color: getBugLevelTextColor2(scope.row.bug_level) }"
                  size="small">
                  {{ getBugLevelName2(scope.row.bug_level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="UpdatedAt" label="更新时间" width="180" />
          </el-table>
        </div>
      </div>

      <!-- 第三行：日报和热点 -->
      <!-- <div class="grid grid-cols-2 gap-6">
        <div class="bg-white rounded-lg p-4 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900">日报记录</h3>
            <el-button type="primary" size="small" class="!rounded-button whitespace-nowrap">
              查看更多
            </el-button>
          </div>
          <div class="space-y-4">
            <div v-for="(report, index) in dailyReports" :key="index" class="flex items-start space-x-4">
              <div class="flex-1">
                <div class="text-gray-900">{{ report.content }}</div>
                <div class="text-sm text-gray-500 mt-1">{{ report.date }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-lg p-4 shadow-sm">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900">热点问题</h3>
            <el-button type="primary" size="small" class="!rounded-button whitespace-nowrap">
              查看更多
            </el-button>
          </div>
          <div class="space-y-4">
            <div v-for="(issue, index) in hotIssues" :key="index" class="flex items-start space-x-4">
              <div class="flex-1">
                <div class="text-gray-900">{{ issue.title }}</div>
                <div class="text-sm text-gray-500 mt-1">{{ issue.description }}</div>
              </div>
              <el-tag :type="issue.priority === '高' ? 'danger' : 'warning'">
                {{ issue.priority }}优先级
              </el-tag>
            </div>
          </div>
        </div>
      </div> -->
    </div>


    <!-- 查看需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible"
      @close="handleCloseDiglog" @closed="handleCloseDiglog" top="8vh">
      <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="true">
      </CommonRequirementInfoVue>
    </el-dialog>

  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import {
  PostGetAllTimeOutIrs,// 获取所有超时任务
  GetGetAllOrMyBugList,// 获取所有未修复的bug
  GetBugStatusList,//获取bug状态列表
} from "@/api/newDemands/index";
import {
  getItemList, //获取所有的待填写任务列表
} from "@/api/common/index";
import { useRouter } from 'vue-router';

const router = useRouter();
const overviewData = ref([
  {
    title: '需求模块',
    total: 156,
    personal: 23,
    viewMode: '图表视图',
    unassigned: 12
  },
  {
    title: '任务模块',
    total: 289,
    personal: 45,
    viewMode: '列表视图'
  },
  {
    title: '用例模块',
    total: 432,
    personal: 67,
    viewMode: '图表视图'
  }
]);


const PRIORITY_COLORS2 = [
  { value: 1, label: "致命", bgColor: "#ff4d4f", textColor: "#fff" },
  { value: 2, label: "严重", bgColor: "#ffc107", textColor: "#fff" },
  { value: 3, label: "一般", bgColor: "#52c41a", textColor: "#fff" },
  { value: 4, label: "建议", bgColor: "#909399", textColor: "#fff" },
];


const getBugLevelName2 = (level: number): string => {
  const levelObj = PRIORITY_COLORS2.find((p) => p.value === level);
  return levelObj ? levelObj.label : '未知等级';
};

const getBugLevelColor2 = (level: number): string => {
  const levelObj = PRIORITY_COLORS2.find((p) => p.value === level);
  return levelObj ? levelObj.bgColor : '#999'; // 默认灰色
};

const getBugLevelTextColor2 = (level: number): string => {
  const levelObj = PRIORITY_COLORS2.find((p) => p.value === level);
  return levelObj ? levelObj.textColor : '#000'; // 默认黑色
};

const detailAllData = {
  需求列表: [
    { name: '电商平台用户体验优化', status: '进行中', owner: '陈思远', date: '2024-01-15' },
    { name: '支付系统安全升级', status: '已完成', owner: '林雨晨', date: '2024-01-14' },
    { name: '移动端性能优化', status: '进行中', owner: '张明睿', date: '2024-01-13' },
    { name: '数据分析平台构建', status: '已完成', owner: '王子豪', date: '2024-01-12' },
    { name: '会员系统重构', status: '进行中', owner: '黄海洋', date: '2024-01-11' },
    { name: '订单管理优化', status: '已完成', owner: '周雪莲', date: '2024-01-10' }
  ],
  超时任务: [
    { name: '首页改版设计评审', status: '已超时', owner: '刘雨欣', date: '2024-01-10' },
    { name: '用户反馈系统开发', status: '即将超时', owner: '赵晓峰', date: '2024-01-14' },
    { name: '性能监控方案制定', status: '已超时', owner: '孙梦琪', date: '2024-01-08' },
    { name: 'API 接口优化', status: '即将超时', owner: '吴俊杰', date: '2024-01-15' },
    { name: '数据备份方案', status: '已超时', owner: '郑小凡', date: '2024-01-07' },
    { name: '安全漏洞修复', status: '即将超时', owner: '李明达', date: '2024-01-13' }
  ]
};

const detailPersonalData = {
  需求列表: [
    { name: '电商平台用户体验优化', status: '进行中', owner: '陈思远', date: '2024-01-15' },
    { name: '移动端性能优化', status: '进行中', owner: '张明睿', date: '2024-01-13' }
  ],
  超时任务: [
    { name: '用户反馈系统开发', status: '即将超时', owner: '赵晓峰', date: '2024-01-14' },
    { name: 'API 接口优化', status: '即将超时', owner: '吴俊杰', date: '2024-01-15' }
  ]
};

const toggleView = (view: string) => {
  myOrAllTimeOutIcs.value = view;
  getAllTimeOutIrs();
};

const toggleBugView = (view: string) => {
  myOrAllBugList.value = view;
  getAllOrMyBugList();
};
const dailyReports = ref([
  { content: '完成电商平台首页改版设计评审，确定核心功能模块布局', date: '2024-01-15 14:30' },
  { content: '优化支付系统性能，提升交易成功率达到99.9%', date: '2024-01-15 11:20' },
  { content: '完成移动端 App 性能优化方案制定，准备进入开发阶段', date: '2024-01-15 09:45' }
]);
const hotIssues = ref([
  { title: '支付系统偶发性超时', description: '在高并发场景下出现支付超时问题', priority: '高' },
  { title: '移动端加载速度慢', description: '首页加载时间超过3秒，影响用户体验', priority: '中' },
  { title: '数据统计不准确', description: '部分用户行为数据统计存在偏差', priority: '中' }
]);



// 获取所有项目名称
const allItems = ref();
const allItemsCopy = ref();
const getAllItems = async () => {
  const { data } = await getItemList()
  if (data.code == 200) {
    allItems.value = data.data;
    allItemsCopy.value = data.data;
  }
}

// 返回项目名称
const getItemName = (id: number) => {
  if (!allItems.value || allItems.value.length === 0) {
    return "未知";
  }
  const itemMap = allItems.value.map((item: any) => ({
    "id": item.ID,
    "itemName": item.itemName,
  }));
  const item = itemMap.find((item: any) => item.id == id)
  return item ? item.itemName : "未知"
}



// 获取 Bug 状态列表
const bugStatusList = ref<any[]>([]); // 从接口获取的 Bug 状态列表
const fetchBugStatusList = async () => {
  try {
    const { data } = await GetBugStatusList();
    if (data.code === 200) {
      bugStatusList.value = data.data; // 存储接口返回的状态列表
    } else {
      console.error("获取 Bug 状态列表失败:", data.msg);
    }
  } catch (error) {
    console.error("获取 Bug 状态列表时发生错误:", error);
  }
};

// 根据状态值获取状态名称
const getBugStatusName = (status: number) => {
  const statusObj = bugStatusList.value.find((s) => s.bug_status === status);
  return statusObj ? statusObj.bug_status_name : '未知状态';
};

// 根据状态值获取状态颜色
const getBugStatusColor = (status: number) => {
  const statusObj = bugStatusList.value.find((s) => s.bug_status === status);
  return statusObj ? statusObj.bugStatusColor : '#999'; // 默认灰色
};


// 获取所有未修复的bug
const myOrAllBugList = ref('my');
const bugListTableData = ref();
const bugListLoading = ref(false);
const getAllOrMyBugList = async () => {
  bugListLoading.value = true;
  const { data } = await GetGetAllOrMyBugList(myOrAllBugList.value)
  if (data.code == 200) {
    bugListTableData.value = data.data;
    bugListLoading.value = false;
  } else {
    ElMessage.error(data.msg);
    bugListLoading.value = false;
  }
};


// 获取所有超时任务
const myOrAllTimeOutIcs = ref('my');
const timeOutTableData = ref<any>([]);
const requirementLoading = ref(false);
const getAllTimeOutIrs = async () => {
  bugListLoading.value = true;
  requirementLoading.value = true;
  const { data } = await PostGetAllTimeOutIrs(myOrAllTimeOutIcs.value)
  if (data.code == 200) {
    timeOutTableData.value = data.data;
    requirementLoading.value = false;
    bugListLoading.value = false;
  } else {
    ElMessage.error(data.msg);
    requirementLoading.value = false;
    bugListLoading.value = false;
  }
};


// TODO 点击需求查看需求详情
const currentRowId = ref(null);// 需求高亮
const dialogInfoVisible = ref(false);// 需求详情弹窗
const isRequirementID = ref<any>(null);// 当前需求ID
const clearData = ref(false);//控制是否清空子组件数据
const handleRequirementInfo = (row: any) => {
  currentRowId.value = row.ID;
  isRequirementID.value = row.itemRequirementId;
  dialogInfoVisible.value = true;
};

// TODO 关闭弹窗
const handleCloseDiglog = () => {
  // 查看需求弹窗
  clearData.value = true;
  dialogInfoVisible.value = false;
};

// TODO Bug动态缺陷
const handleRBugInfo = async (row: any) => {
  console.log("当前bug:", row);
  localStorage.setItem('BugID', row.ID);
  router.push({
    path: '/experiment/bugs',
  })
};

onMounted(() => {
  getAllTimeOutIrs();
  fetchBugStatusList();
  getAllItems();
  getAllOrMyBugList();
});
</script>
<style scoped>
.el-table :deep(.el-table__cell) {
  padding: 8px 0;
}
</style>
